package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.caoben_back.entity.po.LoginParams;
import com.example.caoben_back.entity.po.RegisterParams;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.IUserService;
import com.example.caoben_back.utils.JWTUtil;
import com.example.caoben_back.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    
    @Autowired
    private JWTUtil jwtUtil;

    // 登录
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginParams params) {
        // 实际业务：校验手机号密码，生成token
        User user = userService.getOne(new QueryWrapper<User>()
                .eq("phone", params.getPhone()));
        
        if (user == null) {
            return Result.fail("账号不存在");
        }
        
        // 验证密码
        if (!PasswordUtil.verify(params.getPassword(), user.getPassword(), user.getSalt())) {
            return Result.fail("账号或密码错误");
        }
        
        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userService.updateById(user);
        
        // 生成JWT Token
        String token = JWTUtil.sign(user, jwtUtil.getExpireTime(), jwtUtil.getSecret());
        
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);
        return Result.success(data);
    }

    // 注册
    @PostMapping("/register")
    public Result<Integer> register(@RequestBody RegisterParams params) {
        // 检查手机号是否已被注册
        User existingUser = userService.getOne(new QueryWrapper<User>()
                .eq("phone", params.getPhone()));
        
        if (existingUser != null) {
            return Result.fail("该手机号已被注册");
        }
        
        User user = new User();
        user.setNickname(params.getNickname());
        user.setPhone(params.getPhone());
        user.setUid(params.getUid());
        
        // 生成盐值并加密密码
        String salt = PasswordUtil.generateSalt();
        String encryptedPassword = PasswordUtil.encrypt(params.getPassword(), salt);
        
        user.setPassword(encryptedPassword);
        user.setSalt(salt);
        
        boolean save = userService.save(user);
        return save ? Result.success(user.getUserId()) : Result.fail("注册失败");
    }

    // 获取用户信息
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam Integer userId) {
        User user = userService.getById(userId);
        return Result.success(user);
    }

    // 更新用户信息
    @PutMapping("/update")
    public Result<Boolean> updateUser(@RequestBody User user) {
        return Result.success(userService.updateById(user));
    }

    // 上传头像
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("avatar") MultipartFile file) {
        // 实际业务：上传文件到OSS，返回URL
        String avatarUrl = "https://mock-avatar/" + System.currentTimeMillis() + ".png";
        Map<String, String> data = new HashMap<>();
        data.put("avatarUrl", avatarUrl);
        
        // 实际应该更新用户头像URL
        // 这里为了简化没有实现完整的更新逻辑
        return Result.success(data);
    }
}